/**
 * Created by Arnald on 2017/4/24.
 */
let os = require('os');
let uuid = require('node-uuid');
let log = require('./log.js');
let variable = require('../data/variable.js');
let mem = require('./mem.js');

let util = module.exports;

/**
 * 获得一个随机的uuid
 * @returns {*}
 */
util.uuid = function () {
    return uuid.v4();
};

/**
 *
 * @param socket
 * @returns {string}
 */
util.cid = function (socket) {
    let cid = socket.remoteAddress + ':' + socket.remotePort;
    return cid;
};

util.timeStamp = function () {
    return Math.floor(Date.now() / 1000);
};

/**
 *
 * @param user
 * @returns {{}}
 */
util.userInfo = function (user) {
    let data = {};
    try {
        data.id = user.id;
    } catch (e) {
        log.e('utils/utils.js 42行的错误', user);
    }
    if (user.name) {
        data.name = user.name;
        //data.name = encodeURIComponent(user.name);
    }
    if (user.avatar) {
        data.avatar = user.avatar;
    }
    data.gold = user.gold;
    data.score = user.score;
    data.gem = user.gem;
    if (user.account) {
        data.account = user.account;
    }
    if (user.card) {
        data.card = user.card;
    }   
    if (user.bluedId) {
        data.bluedId = user.bluedId;
    }   
    return data;
};

/**
 *
 * @param item
 * @param time
 * @returns {*}
 */
util.itemInfo = function (item, time) {
    if (!time) {
        time = util.timeStamp();
    }
    if (item.expiredTime == -1) {
        item.restTime = null;
    } else {
        item.restTime = item.expiredTime - time;
    }
    //delete item.expiredTime;

    return item;
};

/**
 *
 * @param message
 * @returns {Array}
 */
util.messageToArr2 = function (message) {
    let arr = [];
    let start = 0;
    console.log('message', message);
    console.log('length', message.length);
    console.log('toString', message.toString());
    while (true) {
        let len = message.readUInt16BE(start);
        console.log('len', len);
        start += 2;
        let str = message.slice(start, start + len).toString();
        console.log(str);
        arr.push(str);
        start = start + len;
        if (start >= message.length) {
            break;
        }
    }
    let list = [];
    for (let i in arr) {
        if (!arr[i]) {
            continue;
        }
        try {
            console.log('arr[i]',i,arr[i]);
            let data = JSON.parse(arr[i]);
            if (arr[i].indexOf('{') < 0) {
                continue;
            }
        } catch (e) {
            //log.p(e);
            continue;
        }
        list.push(data);
    }

    return list;
};
util.messageToArr = function (message, cid) {
    // console.log('正则', msg.match(/(\{.+?\})(?={|$)/g));
    //arr = msg.match(/(\{.+?\})(?={|$)/g);
    let arr = [];
    let msg = '';
    if (mem.tempMessage[cid]) {
        msg = mem.tempMessage[cid] + message.toString();
    } else {
        msg = message.toString();
    }
    if (msg.indexOf('||') >= 0) {
        arr = msg.split('||');
    } else {
        arr.push(msg);
    }
    let list = [];
    for (let i in arr) {
        if (!arr[i]) {
            continue;
        }
        if (!arr[i]) {
            continue;
        }
        if (!arr[i].match(/(\{.+?\})(?={|$)/g)) {
            mem.tempMessage[cid] = arr[i];
            continue;
        }
        let data;
        try {
            data = JSON.parse(arr[i]);
        } catch (e) {
            mem.tempMessage[cid] = arr[i];
            continue;
        }
        list.push(data);
    }
    return list;
};

/**
 *
 * @param json
 * @returns {{}}
 */
util.jsonSort = function (json) {
    //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newKey是一个数组
    let newKey = Object.keys(json).sort();
    console.log('newKey='+newKey);
    let newJson = {}; //创建一个新的对象，用于存放排好序的键值对
    for (let i = 0; i < newKey.length; i++) {
        //遍历newKey数组
        newJson[newKey[i]] = json[newKey[i]];
        //向新创建的对象中按照排好的顺序依次增加键值对
    }
    return newJson; //返回排好序的新对象
};

/**
 * 把对象拼成url
 * @param param
 * @returns {string}
 */
util.paramToUrl = function (param) {
    let params = [];
    for (let i in param) {
        if (param[i] == undefined) {
            continue;
        }
        params.push(i + '=' + param[i]);
    }
    return params.join('&');
};

/**
 * 整合来自请求的参数
 * @param req
 * @returns {{}}
 */
util.getRequestParam = function (req) {
    let data = {};
    for (let k in req.query) {
        data[k] = req.query[k];
    }
    for (let k in req.body) {
        data[k] = req.body[k];
    }
    return data;
};

/**
 * 算起始之间的随机数
 * @param x 起
 * @param y 始
 * @param z 小数点位数
 * @returns {Number}
 */
util.random = function (x, y, z) {
    let w = y - x;
    return parseFloat((Math.random() * w + x).toFixed(z));
};

/**
 * 从一个数组里随机取出一个元素
 * @param arr
 * @returns {*}
 */
util.getRandItemInArray = function (arr) {
    return arr[Math.floor(Math.random() * arr.length)];
};

/**
 * 从一个数组里随机取出多个元素
 * @param arr
 * @param count
 * @returns {Array}
 */
util.getRandItemsInArray = function (arr, count) {
    let result = [];
    for (let i = 0; i < count; i++) {
        let ran = Math.floor(Math.random() * arr.length);
        result.push(arr.splice(ran, 1)[0]);
    }
    return result;
};

/**
 * 获得一个指定类型的随机游戏服务器
 * @param type
 * @returns {*}
 */
util.getRandGameServer = function (type) {
    let ar = [];
    for (let i in variable.game) {
        if (variable.game[i].type != type) {
            continue;
        }
        ar.push(variable.game[i]);
    }
    return util.getRandItemInArray(ar);
};

/**
 * 获得本地的IPv4
 * @returns {*}
 */
util.getLocalIPv4 = function () {
    let IPv4 = null; 
    if (os.platform() == 'linux') {
        if (os.networkInterfaces().eth0) {
            for (let i = 0; i < os.networkInterfaces().eth0.length; i++) {
                if (os.networkInterfaces().eth0[i].family == 'IPv4') {
                    IPv4 = os.networkInterfaces().eth0[i].address;
                }
            }
        } else {
            IPv4 = os.hostname().replace(/-/g, '.');
        }
    } else if (os.platform() == 'win32') {
        IPv4 = '127.0.0.1';
    } else if (os.platform() =="darwin"){
        IPv4 = '127.0.0.1';
    }   
    return IPv4;
};

/**
 * 设置服务器信息
 * @param type
 * @param i
 * @returns {*}
 */
util.setServerInfo = function (type, i) {
    if (variable[type].id) {
        mem.server = {'type': type};
        return true;
    }
    mem.server = {'type': type, 'key': i};
    return true;
};

/**
 * 拉取服务器信息
 * @param key
 * @returns {*}
 */
util.getServerInfo = function (key) {
    if (!mem.server.key) {
        return variable[mem.server.type][key];
    }
    return variable[mem.server.type][mem.server.key][key];
};

/**
 * 获得房间号对应的服务器数据
 * @param gameId
 * @returns {*}
 */
util.getGameIdServer = function (gameId) {
    if (gameId.length <= 10) {
        gameId = parseInt(gameId, 16);
    }
    let id = parseInt(gameId.toString().substr(0, 4));
    return variable.game[variable.gameIdx[id]];
};


util.roundTable = (table) => {
    if (Object.keys(table).length == 0) {
        return false;
    }
    let tmp = {};
    for (let i in table) {
        if (!table[i]) {
            continue;
        }
        tmp[i] = table[i];
    }
    let roundTable = {};
    let max = 0;
    for (let key in table) {
        max += table[key];
        roundTable[key] = max;
    }
    let rand = util.random(0, (max - 1));
    let now = 0;
    for (let key in roundTable) {
        let val = roundTable[key];
        if (rand >= now && rand < val) {
            return key;
        } else {
            now = val;
        }
    }
    return false;
};

/**
 * @getClientIP
 * @desc 获取用户 ip 地址
 * @param {Object} req - 请求
 */
util.getClientIP = function(req) {
    return req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
        req.connection.remoteAddress || // 判断 connection 的远程 IP
        req.socket.remoteAddress || // 判断后端的 socket 的 IP
        req.connection.socket.remoteAddress;
};